package Servlet;

import User.*;
import Utils.DBCPjdbc;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;


@WebServlet(value = "/login")
public class login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 连接数据库
        QueryRunner qr = new QueryRunner(DBCPjdbc.getBs());
        List<User> query = null;
        try {
                    query = qr.query("select * from user where username = ? and `password` = ?",
                    new BeanListHandler<>(User.class)
                    , username, password);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        if (query.size()!=0){
            // 登录成功，跳转到主页
            response.getWriter().write("<h3>登录成功</h3>");
        }
        else {
            // 登录失败，跳转到登录页面
            response.getWriter().write("<h3>登录失败</h3>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
